package com.zja.www.controller;


import com.zja.www.bean.Result;
import com.zja.www.entity.Doctor;
import com.zja.www.entity.MedicalRecord;
import com.zja.www.service.DoctorService;
import com.zja.www.service.MedicalRecordService;
import com.zja.www.service.UserService;
import java.sql.Timestamp;
import java.util.List;

public class DoctorController extends BaseController {
    private final DoctorService doctorService;
    private final MedicalRecordService medicalRecordService;
    private int currentDoctorId;

    public DoctorController(UserService userService,
                            DoctorService doctorService,
                            MedicalRecordService medicalRecordService) {
        super(userService, doctorService, medicalRecordService);
        this.doctorService = doctorService;
        this.medicalRecordService = medicalRecordService;
    }


    public Result login(String name, String password) {
        Result result = doctorService.login(name, password);
        if (result.isSuccess()) {
            this.currentDoctorId = ((Doctor)result.getData()).getId();
        }
        return result;
    }

    /**
     * 获取当天记录（包含预约和挂号）
     */
    public List<MedicalRecord> getTodayRecords() {
        return medicalRecordService.getRecordsByDoctorAndDate(
                currentDoctorId,
                new Timestamp(System.currentTimeMillis())
        );
    }

    /**
     * 获取指定日期记录（包含预约和挂号）
     */
    public List<MedicalRecord> getRecordsByDate(Timestamp date) {
        return medicalRecordService.getRecordsByDoctorAndDate(currentDoctorId, date);
    }

    /**
     * 更新记录状态（统一处理预约/挂号）
     */
    public boolean updateRecordStatus(int recordId, String newStatus) {

        if (!isValidStatus(newStatus)) {
            return false;
        }
        return medicalRecordService.updateRecordStatus(recordId, newStatus);
    }

    /**
     * 获取医生信息
     */
    public Doctor getDoctorInfo() {
        return doctorService.getDoctorById(currentDoctorId);
    }

    /**
     * 取消记录（专用方法）
     */
    public boolean cancelRecord(int recordId) {
        return medicalRecordService.cancelRecord(recordId);
    }

    /**
     * 退出登录
     */
    public void logout() {
        this.currentDoctorId = 0;
    }


    /**
     * 更新密码
     */
    public Result updatePassword(int id, String newPassword) {
        Doctor doctor = doctorService.getDoctorById(id);
        if (doctor == null) {
            return Result.fail("用户不存在");
        }
        doctor.setPassword(newPassword);
        boolean success = doctorService.updateDoctor(doctor);
        return success ? Result.success("密码更新成功", null) : Result.fail("密码更新失败");
    }


    private boolean isValidStatus(String status) {
        return status.equals(MedicalRecord.STATUS_PENDING) ||
                status.equals(MedicalRecord.STATUS_CONFIRMED) ||
                status.equals(MedicalRecord.STATUS_CANCELLED) ||
                status.equals(MedicalRecord.STATUS_COMPLETED);
    }

}
